import request from '@/utils/request'
import QRCode from 'qrcode'

// 查询商家列表
export function listMerchant(query) {
  return request({
    url: '/ruoyi-activity/merchant/list',
    method: 'get',
    params: query
  }).then(response => {
    const merchants = response.rows;
    const promises = merchants.map(merchant => generateQrCode(merchant));
    return Promise.all(promises).then(() => response);
  });
}

// 查询商家详情
export function getMerchant(id) {
  return request({
    url: '/ruoyi-activity/merchant/' + id,
    method: 'get'
  }).then(response => {
    return generateQrCode(response.data).then(() => response);
  });
}

// 新增商家
export function addMerchant(data) {
  return request({
    url: '/ruoyi-activity/merchant',
    method: 'post',
    data: data
  });
}

// 修改商家
export function updateMerchant(data) {
  return request({
    url: '/ruoyi-activity/merchant',
    method: 'put',
    data: data
  });
}

// 删除商家
export function delMerchant(id) {
  return request({
    url: '/ruoyi-activity/merchant/' + id,
    method: 'delete'
  });
}

/**
 * 为商家对象生成二维码
 * @param {Object} merchant 商家对象
 */
export function generateQrCode(merchant) {
  const { merchantCodeUrl, id } = merchant;
  if (!merchantCodeUrl || !id) return Promise.resolve();

  const fullUrl = `${merchantCodeUrl}${merchantCodeUrl.includes('?') ? '&' : '?'}merchantId=${encodeURIComponent(id)}`;

  return QRCode.toDataURL(fullUrl)
    .then(qrCodeDataUrl => {
      merchant.qrCodeUrl = qrCodeDataUrl;
      merchant.merchantCodeUrl = fullUrl;
      return merchant;
    })
    .catch(error => {
      merchant.qrCodeUrl = null;
      return merchant;
    });
}
